package com.sunlands.qdcy.deskmate.web;


import com.alibaba.fastjson.JSON;
import com.google.common.base.Joiner;
import com.sunlands.qdcy.deskmate.client.UserCenterService;
import com.sunlands.qdcy.deskmate.constant.AppEnum;
import com.sunlands.qdcy.deskmate.constant.CommonResultMessage;
import com.sunlands.qdcy.deskmate.enums.CodeMsgType;
import com.sunlands.qdcy.deskmate.vo.BusinessResult;
import com.sunlands.qdcy.deskmate.vo.ResultVO;
import com.sunlands.qdcy.deskmate.vo.feign.UserInfoVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.AuthorizationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

@Slf4j
public class BaseController {

    public static Object[] arg = new Object[] {};

    public <T> ResultVO<T> successState() {

        ResultVO<T> resultVO = new ResultVO<>();

        resultVO.setCode(CodeMsgType.state_success.getCode());
        resultVO.setMessage(CodeMsgType.state_success.getMsg());

        return resultVO;
    }

    public <T> ResultVO<T> successState(T content) {

        ResultVO<T> resultVO = new ResultVO<>();

        resultVO.setCode(CodeMsgType.state_success.getCode());
        resultVO.setMessage(CodeMsgType.state_success.getMsg());
        resultVO.setData(content);

        return resultVO;
    }

    public <T> ResultVO<T> successState(T content , String message) {

        ResultVO<T> resultVO = new ResultVO<>();

        resultVO.setCode(CodeMsgType.state_success.getCode());
        resultVO.setMessage(message);
        resultVO.setData(content);

        return resultVO;
    }

    public <T> ResultVO<T> failState(String message) {

        ResultVO<T> resultVO = new ResultVO<>();

        resultVO.setCode(CodeMsgType.state_fail.getCode());
        resultVO.setMessage(message);

        return resultVO;
    }

    public <T> ResultVO<T> failState(String message, T content) {

        ResultVO<T> resultVO = new ResultVO<>();

        resultVO.setCode(CodeMsgType.state_fail.getCode());
        resultVO.setMessage(message);
        resultVO.setData(content);

        return resultVO;
    }
    public ResultVO getPramaErrorJson(String message) {
        ResultVO resultVO = new ResultVO();
        resultVO.setCode(1);
        resultVO.setMessage(message);
        return resultVO;
    }

    public String getAppIdFromHeader(HttpServletRequest request) throws Exception{
        String appId = request.getHeader("appId");
        if(StringUtils.isEmpty(appId)){
            throw new Exception("参数异常");
        }
        return appId;
    }

    @Autowired
    UserCenterService userCenterService;

    @Autowired
    RedisTemplate redisTemplate;

    /**
     * 敏感词校验
     * 如果包含敏感词则返回true
     *
     * @param word
     * @return
     */
//    protected boolean checkSensitiveWord(String word) {
//        Map<String, Object> param = new HashMap<>();
//        param.put("word", word);
//        try {
//            String result = HttpUtil.doPost(wordsFilterUrl, param);
//            JSONObject jsonObject = JSON.parseObject(result);
//            if (jsonObject.getBoolean("content")) {
//                return true;
//            }
//        } catch (Exception e) {
//            log.error("敏感词校验异常，url={},param={},e={}", wordsFilterUrl, JSON.toJSONString(param), e);
//        }
//        return false;
//    }

    /**
     * 没有用户登录的情况下，security会返回anonymousUser
     */
    public static final String ANONYMOUS_USER = "anonymousUser";

    /**
     * 该方法不需要访问其他服务，可以在security中获取到用户的用户名和id
     *
     * @return UserInfoDTO
     */
    protected Long currentUserId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Object object = authentication.getPrincipal();

        if (object instanceof String) {
            if (ANONYMOUS_USER.equals(object)) {
                return null;
            }
            String[] strings = ((String) object).split("-");
            if (strings.length == 2) {
                return Long.parseLong(strings[1]);
            } else {
                throw new AuthorizationServiceException("client token无法获取到用户信息！");
            }
        } else {
            try {
                throw new AuthorizationServiceException("没有获取到用户线信息！");
            } catch (AuthenticationException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 该方法会调用微服务tz-user-center来获取用户基本信息
     *
     * @return UserInfoDTO
     */
    protected UserInfoVO currentUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Object object = authentication.getPrincipal();
        if (object instanceof String) {
            String[] strings = ((String) object).split("-");
            if (strings.length == 2) {
                UserInfoVO userInfoDTO = userCenterService.getUserInfoById(Long.parseLong(strings[1])).getData();
                return userInfoDTO;
            } else {
                throw new AuthorizationServiceException("client token无法获取到用户信息！");
            }
        } else {
            try {
                throw new AuthorizationServiceException("没有获取到用户线信息！");
            } catch (AuthenticationException e) {
                e.printStackTrace();
            }
        }
        return null;
    }


    protected UserInfoVO getByUserId(Long userId) {
        if (userId == null || userId.intValue() == 0) {
            return null;
        }
        try {
            BusinessResult<UserInfoVO> businessResult = userCenterService.getUserInfoById(userId);
            if (businessResult.getCode().longValue() == CommonResultMessage.SUCCESS.code) {
                return businessResult.getData();
            } else {
                log.error("获取用户信息失败，id = {} , res = {} ", userId, JSON.toJSONString(businessResult));
            }
        } catch (Exception ex) {
            log.error("获取用户信息失败，id = {} , ex = {} ", userId, ex);
        }
        return null;
    }



    /**
     * 获取图片上传的拼接路径
     * @return String
     */
    protected String getUploadImgPath() {
        return Joiner.on("/").join("tongzhuo", "user", "diary").concat("/");
    }

    public String getApp(HttpServletRequest request) {
        String app = request.getHeader("app");
        app = (Objects.nonNull(app) && AppEnum.postgraduate.name().equals(app)) ?
                AppEnum.postgraduate.name() : AppEnum.tongzhuo.name();
        return app;
    }

}